//
//  ChengShiXiangQing.m
//  MDDNew
//
//  Created by 孙昊坤 on 15/10/29.
//  Copyright © 2015年 heqing. All rights reserved.
//

#pragma mark -- 城市详情页面

#import "ChengShiXiangQing.h"

// 宽高
#define Kheight [UIScreen mainScreen].bounds.size.height
#define Kwidth [UIScreen mainScreen].bounds.size.width

// 导入解析类
#import "TYDataManager.h"

// 轮播图
#import "SDCycleScrollView.h"

#import "UIImageView+WebCache.h"

#import "UIView+WLFrame.h"

// 导入自由行
#import "ZYXCell.h"

// 导入跳转的精彩当地游（跳转）
#import "JingChaiDangDIYou.h"
// 导入城市超级自由行
#import "ChengShiChaoJiZhiYouXing.h"

// 导入超级自由行和精彩当地游（全部）
#import "JingChaiHeZhouYouXing.h"

// 导入城市详细接收
#import "ChengShiXiangXiJieShao.h"


@interface ChengShiXiangQing ()<UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>

@property (nonatomic, strong) UITableView *tableView;

// 创建字典保存数据
@property (nonatomic, strong) NSDictionary *dataDic;

// 表示图
@property (nonatomic, strong) UICollectionView *collectionView;

@end

@implementation ChengShiXiangQing

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self jieXi];
    
    
    
    [self addUITableView];
    
    [self addUICollectionView];
}

// 解析数据
- (void)jieXi
{
    NSString *string = [NSString stringWithFormat:@"http://open.qyer.com/qyer/footprint/city_detail?city_id=%@", self.ids];
    
    NSString *string2 = [string stringByAppendingString:@"&client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&lat=40.02932332771707&lon=116.3373332060144&page=1&track_app_channel=App%2520Store&track_app_version=6.8&track_device_info=iPhone7%2C1&track_deviceid=3D292DEC-1F82-4FE7-9AE7-A1866F5F24E7&track_os=ios%25209.0.2&v=1"];
    
    [[TYDataManager shareManager] requestDataWithUrl:string2 block:^(NSData *data){
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        _dataDic = [dic valueForKey:@"data"];
        
        [_tableView reloadData];
        [_collectionView reloadData];
    }];
}

// 布局
- (void)addUITableView
{
    _tableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [self.view addSubview:_tableView];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    } else if (section == 1) {
        NSArray *array = [_dataDic valueForKey:@"local_discount"];
        if (array.count == 0) {
            return 1;
        }
        return 2;
    } else {
        NSArray *array = [_dataDic valueForKey:@"new_discount"];
        if (array.count == 0) {
            return 0;
        }
        return array.count + 1;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *string = @"MyCell";
    ZYXCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (cell == nil) {
        cell = [[ZYXCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:string];
    }
    
    if (indexPath.section == 0 && indexPath.row == 0) {
        // 照片数组
        NSArray *imagesURLStrings = [_dataDic valueForKey:@"photos"];
        
        //网络加载 --- 创建带标题的图片轮播器
        SDCycleScrollView *cycleScrollView2 = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, Kwidth, 220) imageURLStringsGroup:nil]; // 模拟网络延时情景
        cycleScrollView2.pageControlAliment = SDCycleScrollViewPageContolAlimentRight;
        cycleScrollView2.dotColor = [UIColor yellowColor]; // 自定义分页控件小圆标颜色
        cycleScrollView2.placeholderImage = [UIImage imageNamed:@"placeholder"];
        // 隐藏圆表
        cycleScrollView2.showPageControl = NO;
        [cell addSubview:cycleScrollView2];
        
        //             --- 模拟加载延迟
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            cycleScrollView2.imageURLStringsGroup = imagesURLStrings;
        });
        
        // 城市介绍
        UILabel *mingCheng = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, 100, 25)];
        mingCheng.text = [_dataDic valueForKey:@"cnname"];
        mingCheng.textColor = [UIColor whiteColor];
        mingCheng.font = [UIFont systemFontOfSize:25];
        [cell addSubview:mingCheng];
        
        UILabel *yingWen = [[UILabel alloc] initWithFrame:CGRectMake(mingCheng.left, mingCheng.bottom + 3,  Kwidth, 15)];
        yingWen.textColor = [UIColor whiteColor];
        yingWen.text = [_dataDic valueForKey:@"enname"];
        yingWen.font = [UIFont systemFontOfSize:15];
        [cell addSubview:yingWen];
        
        UILabel *jieShao = [[UILabel alloc] initWithFrame:CGRectMake(yingWen.left, yingWen.bottom + 10, Kwidth - 100, 30)];
        jieShao.numberOfLines = 2;
        jieShao.font = [UIFont systemFontOfSize:12];
        jieShao.textColor = [UIColor whiteColor];
        jieShao.text = [_dataDic valueForKey:@"entryCont"];
        [cell addSubview:jieShao];
        
        UIButton *jianJie = [UIButton buttonWithType:UIButtonTypeCustom];
        [jianJie setTitle:@"城市详细介绍" forState:UIControlStateNormal];
        jianJie.frame = CGRectMake(Kwidth - 150, jieShao.bottom + 5, 130, 20);
        jianJie.titleLabel.font = [UIFont systemFontOfSize:12];
        [jianJie addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchUpInside];
        [cell addSubview:jianJie];
        
    }
    if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            NSArray *array = [_dataDic valueForKey:@"local_discount"];
            if (array.count == 0) {
                cell.textLabel.text = @"暂无详细信息";
            } else {
                cell.textLabel.text = @"精彩当地游";
                cell.textLabel.textColor = [UIColor grayColor];
                cell.textLabel.font = [UIFont systemFontOfSize:15];
                
                // 添加查看全部
                UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(Kwidth - 90, cell.textLabel.top - 3, 90, cell.height)];
                lable.text = @"查看全部 >";
                lable.font = [UIFont systemFontOfSize:13];
                lable.alpha = 0.6;
                [cell addSubview:lable];
            }
            
        } else {
            [cell addSubview:_collectionView];
        }
    }
    
    if (indexPath.section == 2) {
            NSArray *array = [_dataDic valueForKey:@"new_discount"];
        if (array.count > 0) {
            if (indexPath.row == 0) {
                cell.textLabel.text = @"超级自由行";
                cell.textLabel.textColor = [UIColor grayColor];
                cell.textLabel.font = [UIFont systemFontOfSize:15];
                
                // 添加查看全部
                UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(Kwidth - 90, cell.textLabel.top - 3, 90, cell.height)];
                lable.text = @"查看全部 >";
                lable.font = [UIFont systemFontOfSize:13];
                lable.alpha = 0.6;
                [cell addSubview:lable];
            } else {
                [cell.tuPian sd_setImageWithURL:[array[indexPath.row - 1] valueForKey:@"photo"]];
                cell.biaoTi.text = [array[indexPath.row - 1]valueForKey:@"title"];
                cell.zheKou.text = [array[indexPath.row - 1]valueForKey:@"priceoff"];
                // 加个
                NSMutableString *jiaGe = [NSMutableString stringWithString:[array[indexPath.row - 1] valueForKey:@"price"]];
                NSRange range = NSMakeRange(0, 4);
                [jiaGe deleteCharactersInRange:range];
                
                NSString *str = [jiaGe stringByReplacingOccurrencesOfString:@"</em>" withString:@""];
                
                cell.jiaGe.text = str;
            }
            
        }
        
        
    }
    
    return cell;
}

- (void)action:(UIButton *)button
{
    ChengShiXiangXiJieShao *viewVC = [[ChengShiXiangXiJieShao alloc] init];
    viewVC.ids = [_dataDic valueForKey:@"id"];
    [self.navigationController pushViewController:viewVC animated:YES];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 220;
    }
    if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            return 40;
        } else {
            return 360;
        }
    }
    if (indexPath.section == 2 && indexPath.row == 0) {
        return 40;
    }
    return 70;
}

// 添加表视图
- (void)addUICollectionView
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    
    // 行边距 (相对于 上下滑动) 如果左右滑动 就是列边距
//    layout.minimumLineSpacing = 30;
    
    // 列边距 (相对于 上下滑动) 如果左右滑动 就是行边距
//    layout.minimumInteritemSpacing = 30;
    
    // 设置宽高
    layout.itemSize = CGSizeMake(Kwidth / 2 - 5, 160);
    
    // 设置滑动方向 (默认是上下滑动的)
//    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    // 表头表尾 只有高度有效果
    
    // 设置内边距
    layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    
    // 初始化 集合视图
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, Kwidth, 360) collectionViewLayout:layout];
    
    // 设置代理
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    
    // collectionView默认是黑的
    _collectionView.backgroundColor = [UIColor whiteColor];
    
    // 注册 你要用的cell
    // Identifier 重用标识符 要一致
    // Class你的cell是那个类 就填那个类
    // 使用系统的就注册系统的 如果自定义的话 就注册自定义的
    [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"MyCell"];
}

// 表示图点击
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    JingChaiDangDIYou *viewVC = [[JingChaiDangDIYou alloc] init];
    viewVC.ids = [[_dataDic valueForKey:@"local_discount"][indexPath.row]valueForKey:@"id"];
    [self.navigationController pushViewController:viewVC animated:YES];
}

#pragma mark -- 代理方法 --

// 必须实现的两个方法 个tableView一样

// 返回每个分区的Item数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
     NSArray *array = [_dataDic valueForKey:@"local_discount"];
    return array.count;
}

// 返回每个item的方法
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    // 这个方法里面 包括了 咱们之前创建tableViewCell写的一堆
    // 必须有一步 必须要有 注册cell
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MyCell" forIndexPath:indexPath];
    
    // 系统没有像tableView一样 给咱们提供布局方式
    // 咱们要使用UICollectionViewCell 一般都是自定义再使用 跟tableView一样 所有的自定义控件都要加在contentView上面
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, Kwidth / 2 - 15, 110)];
    imageView.backgroundColor = [UIColor grayColor];
    NSArray *array = [_dataDic valueForKey:@"local_discount"];
    [imageView sd_setImageWithURL: [array[indexPath.row] valueForKey:@"photo"]];
    [cell addSubview:imageView];
    
    UILabel *miaoSha = [[UILabel alloc] initWithFrame:CGRectMake(5, imageView.bottom + 5, imageView.width, 35)];
    miaoSha.font = [UIFont systemFontOfSize:13];
    miaoSha.numberOfLines = 2;
    miaoSha.text = [array[indexPath.row] valueForKey:@"title"];
    [cell addSubview:miaoSha];
    
    UILabel *zeKou = [[UILabel alloc] initWithFrame:CGRectMake(miaoSha.left, miaoSha.bottom, 40, 20)];
    zeKou.font = [UIFont systemFontOfSize:12];
    zeKou.textColor = [UIColor grayColor];
    zeKou.text = [array[indexPath.row] valueForKey:@"priceoff"];
    [cell addSubview:zeKou];
    
    UILabel *jiaGe = [[UILabel alloc] initWithFrame:CGRectMake(imageView.width - 70 , zeKou.top, 70, 20)];
    // 加个
    NSMutableString *jiaGe2 = [NSMutableString stringWithString:[array[indexPath.row] valueForKey:@"price"]];
    NSRange range = NSMakeRange(0, 4);
    [jiaGe2 deleteCharactersInRange:range];
    
    NSString *str = [jiaGe2 stringByReplacingOccurrencesOfString:@"</em>" withString:@""];
    jiaGe.textColor = [UIColor orangeColor];
    
    jiaGe.text = str;
    
    [cell addSubview:jiaGe];
    
    return cell; // 不需要释放
}

// 返回分区数 根tableview一样 默认就一个分区
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 2 && indexPath.row != 0) {
        ChengShiChaoJiZhiYouXing *viewVC = [[ChengShiChaoJiZhiYouXing alloc] init];
        viewVC.ids = [[_dataDic valueForKey:@"new_discount"][indexPath.row - 1]valueForKey:@"id"];
        [self.navigationController pushViewController:viewVC animated:YES];
    }
    
    // 判断是否符合跳转到合并的自由行和精彩的标准
    NSArray *array =[_dataDic valueForKey:@"new_discount"];
    NSArray *array2 = [_dataDic valueForKey:@"local_discount"];
    if (array.count != 0 && array2.count >= 4) {
        // 跳转到合并的自由行和精彩
        if (indexPath.section == 1 && indexPath.row == 0) {
            JingChaiHeZhouYouXing *viewVC = [[JingChaiHeZhouYouXing alloc] init];
            viewVC.ids = [_dataDic valueForKey:@"id"];
            [self.navigationController pushViewController:viewVC animated:YES];
        }
        
        if (indexPath.section == 2 && indexPath.row == 0) {
            JingChaiHeZhouYouXing *viewVC = [[JingChaiHeZhouYouXing alloc] init];
            viewVC.ids = [_dataDic valueForKey:@"id"];
            [self.navigationController pushViewController:viewVC animated:YES];
        }
    } else {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"内容已在本界面全部显示" delegate:self cancelButtonTitle:@"返回" otherButtonTitles: nil];
            [alert show];
        
        
    }
    
    
}

// 接口 http://open.qyer.com/qyer/footprint/city_detail?city_id=20&client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&lat=40.02932332771707&lon=116.3373332060144&page=1&track_app_channel=App%2520Store&track_app_version=6.8&track_device_info=iPhone7%2C1&track_deviceid=3D292DEC-1F82-4FE7-9AE7-A1866F5F24E7&track_os=ios%25209.0.2&v=1


@end
